<template>
  <el-dialog
    title="批量复制考核方案"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="copy-content">
      <!-- 源教学任务信息 -->
      <el-card v-if="sourceMission" class="source-card" style="margin-bottom: 20px;">
        <template #header>
          <div class="card-header">
            <span>源考核方案</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程名称">{{ sourceMission.courseName }}</el-descriptions-item>
          <el-descriptions-item label="课程编码">{{ sourceMission.courseCode }}</el-descriptions-item>
          <el-descriptions-item label="学期">{{ sourceMission.termName }}</el-descriptions-item>
          <el-descriptions-item label="教师">
            <span v-if="sourceMission.teacherNames && sourceMission.teacherNames.length > 0">
              {{ sourceMission.teacherNames.join(', ') }}
            </span>
            <span v-else>未分配</span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 源考核方案详情 -->
        <div v-if="sourceExamParts.length > 0" style="margin-top: 15px;">
          <h4 style="margin: 10px 0; color: #303133; font-size: 14px;">考核方案组成：</h4>
          <el-table :data="sourceExamParts" size="small" border>
            <el-table-column prop="name" label="考核组成" width="120" />
            <el-table-column prop="proportion" label="比例" width="80">
              <template #default="scope">{{ scope.row.proportion }}%</template>
            </el-table-column>
            <el-table-column prop="scoreTypeName" label="计分方式" width="100" />
            <el-table-column label="考核类型" width="90">
              <template #default="scope">
                <el-tag 
                  v-if="scope.row.examPartType === 'FORMATIVE'" 
                  type="success" 
                  size="small"
                >
                  形成性
                </el-tag>
                <el-tag 
                  v-else-if="scope.row.examPartType === 'FINAL'" 
                  type="warning" 
                  size="small"
                >
                  终结性
                </el-tag>
                <el-tag v-else type="info" size="small">其它</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 目标教学任务选择 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <span>选择目标教学任务</span>
            <div class="header-actions">
              <el-checkbox 
                v-model="selectAll" 
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              >
                全选
              </el-checkbox>
              <span class="selected-count">已选择 {{ selectedTargets.length }} 个</span>
            </div>
          </div>
        </template>

        <div v-loading="loadingTargets">
          <el-alert
            v-if="targetMissions.length === 0 && !loadingTargets"
            title="没有找到可复制的目标教学任务"
            description="同学期同课程的其他教学任务已设置考核方案，或不存在符合条件的教学任务。"
            type="info"
            :closable="false"
            show-icon
          />

          <el-checkbox-group v-model="selectedTargets" v-if="targetMissions.length > 0">
            <div class="missions-grid">
              <el-card 
                v-for="mission in targetMissions" 
                :key="mission.id"
                class="mission-card"
                :class="{ 'selected': selectedTargets.includes(mission.id) }"
                shadow="hover"
              >
                <div class="mission-checkbox">
                  <el-checkbox :label="mission.id">
                    <div class="mission-info">
                      <div class="mission-title">{{ mission.courseName }}</div>
                      <div class="mission-details">
                        <div class="detail-item">
                          <span class="label">编码：</span>
                          <span>{{ mission.courseCode }}</span>
                        </div>
                        <div class="detail-item">
                          <span class="label">学期：</span>
                          <span>{{ mission.termName }}</span>
                        </div>
                        <div class="detail-item">
                          <span class="label">教师：</span>
                          <span>{{ mission.teacherNames?.join(', ') || '未分配' }}</span>
                        </div>
                        <div class="detail-item">
                          <span class="label">学生：</span>
                          <span>{{ mission.studentCount || 0 }} 人</span>
                        </div>
                      </div>
                    </div>
                  </el-checkbox>
                </div>
              </el-card>
            </div>
          </el-checkbox-group>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCopy"
          :loading="copying"
          :disabled="selectedTargets.length === 0"
        >
          复制到 {{ selectedTargets.length }} 个教学任务
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { courseExamPartApi, courseExamPartApiExt } from '@/api/course-exam-part'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  sourceMission: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'copy-success'])

// 响应式数据
const loadingTargets = ref(false)
const copying = ref(false)
const targetMissions = ref([])
const selectedTargets = ref([])
const sourceExamParts = ref([])
const selectAll = ref(false)

// 计算属性
const isIndeterminate = computed(() => {
  const selectedCount = selectedTargets.value.length
  return selectedCount > 0 && selectedCount < targetMissions.value.length
})

// 全选处理
const handleSelectAll = (checked) => {
  if (checked) {
    selectedTargets.value = targetMissions.value.map(mission => mission.id)
  } else {
    selectedTargets.value = []
  }
}

// 监听选中状态变化
watch(selectedTargets, (newVal) => {
  if (newVal.length === 0) {
    selectAll.value = false
  } else if (newVal.length === targetMissions.value.length) {
    selectAll.value = true
  } else {
    selectAll.value = false
  }
}, { deep: true })

// 获取源考核方案
const fetchSourceExamParts = async () => {
  if (!props.sourceMission?.id) return
  
  try {
    const response = await courseExamPartApi.getExamPartsByTeachingMission(props.sourceMission.id)
    sourceExamParts.value = response || []
  } catch (error) {
    console.error('获取源考核方案失败:', error)
    ElMessage.error('获取源考核方案失败')
  }
}

// 获取目标教学任务列表
const fetchTargetMissions = async () => {
  if (!props.sourceMission?.id) return
  
  loadingTargets.value = true
  try {
    const response = await courseExamPartApiExt.getTargetMissionsForCopy(props.sourceMission.id)
    targetMissions.value = response || []
    
    if (targetMissions.value.length === 0) {
      ElMessage.info('没有找到可复制的目标教学任务')
    }
  } catch (error) {
    console.error('获取目标教学任务失败:', error)
    ElMessage.error('获取目标教学任务失败')
    targetMissions.value = []
  } finally {
    loadingTargets.value = false
  }
}

// 执行复制
const handleCopy = async () => {
  if (selectedTargets.value.length === 0) {
    ElMessage.warning('请选择要复制到的教学任务')
    return
  }

  if (sourceExamParts.value.length === 0) {
    ElMessage.warning('源教学任务没有考核方案，无法复制')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要将考核方案复制到选中的 ${selectedTargets.value.length} 个教学任务吗？此操作将覆盖目标教学任务的现有考核方案。`,
      '确认复制',
      {
        confirmButtonText: '确定复制',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    copying.value = true
    
    await courseExamPartApiExt.copyExamPartsToOtherMissions(
      props.sourceMission.id,
      selectedTargets.value
    )
    
    ElMessage.success(`成功复制考核方案到 ${selectedTargets.value.length} 个教学任务`)
    emit('copy-success', selectedTargets.value.length)
    handleClose()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('复制考核方案失败:', error)
      const errorMessage = error.response?.data?.message || error.message || '复制失败'
      ElMessage.error(`复制考核方案失败: ${errorMessage}`)
    }
  } finally {
    copying.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  // 重置数据
  selectedTargets.value = []
  selectAll.value = false
  targetMissions.value = []
  sourceExamParts.value = []
}

// 监听对话框显示状态
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.sourceMission?.id) {
    fetchSourceExamParts()
    fetchTargetMissions()
  }
})

onMounted(() => {
  if (props.visible && props.sourceMission?.id) {
    fetchSourceExamParts()
    fetchTargetMissions()
  }
})
</script>

<style scoped>
.copy-content {
  max-height: 70vh;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selected-count {
  color: #409EFF;
  font-size: 12px;
}

.missions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
}

.mission-card {
  transition: all 0.3s;
  cursor: pointer;
}

.mission-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.mission-card.selected {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.mission-checkbox {
  width: 100%;
}

.mission-checkbox :deep(.el-checkbox) {
  width: 100%;
  align-items: flex-start;
}

.mission-checkbox :deep(.el-checkbox__label) {
  width: 100%;
  padding-left: 8px;
}

.mission-info {
  width: 100%;
}

.mission-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.4;
}

.mission-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item {
  display: flex;
  font-size: 12px;
  line-height: 1.5;
}

.detail-item .label {
  color: #909399;
  min-width: 36px;
  flex-shrink: 0;
}

.detail-item span:last-child {
  color: #606266;
  word-break: break-all;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.source-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.source-card :deep(.el-card__header) {
  background: rgba(255, 255, 255, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.source-card :deep(.el-descriptions__label) {
  color: rgba(255, 255, 255, 0.9);
}

.source-card :deep(.el-descriptions__content) {
  color: white;
}

.source-card h4 {
  color: rgba(255, 255, 255, 0.9);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .missions-grid {
    grid-template-columns: 1fr;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;
  }
}
</style>